<?php

namespace app\controller\sys;

use think\Exception;
use think\facade\App;
use think\facade\Db;
use think\facade\Config;
use think\facade\View;

use app\utils\ReUtils;
use app\model\SysLoginNote as LoginNoteModel;
use app\model\SysMenu as SysMenuModel;
use app\model\Article as ArticleModel;
use app\model\GuestBook as GuestBookModel;
use app\model\Industry as IndustryModel;

class Index extends Base
{
    public function index()
    {
        // 系统信息
        $mysqlVersion = Db::query('SELECT VERSION() AS ver');
        $config       = [
            'url'             => $_SERVER['HTTP_HOST'],
            'document_root'   => $_SERVER['DOCUMENT_ROOT'],
            'server_os'       => PHP_OS,
            'server_port'     => $_SERVER['SERVER_PORT'],
            'server_ip'       => isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '',
            'server_soft'     => $_SERVER['SERVER_SOFTWARE'],
            'php_version'     => PHP_VERSION,
            'mysql_version'   => $mysqlVersion[0]['ver'],
            'max_upload_size' => ini_get('upload_max_filesize'),
            'tp_version'         => App::version(),
        ];

        $userid = (int) session('adminuser.userid');

        $dataLogin = LoginNoteModel::where('userid', $userid)->order('id desc')->limit(10)->select();

        // 快捷方式
        $indexButton = SysMenuModel::getIndexButton();
        $menuList = SysMenuModel::getMenuList();

        View::assign([
            'config'        => $config,
            'dataLogin'     => $dataLogin,
            'indexButton'   => $indexButton,
            'menuList'      => $menuList,
            // 'user'          => $user,
            // 'message'       => $message ?? 0,
            // 'messageCatUrl' => $messageCatUrl,
            'indexTips'     => $this->getIndexTips(),
            'sys_version'  => '0.0.1'
        ]);

        return View::fetch('index');
    }

    // 检查提示信息
    private function getIndexTips()
    {
        $user = $this->getSysUser();

        $defaultPassword = Config::get('app.default_password') ?: 'admin';

        if ($user->password == md5($defaultPassword . $user->salt)) {
            return '<h6 class="mb-0"><i class="icon fas fa-fw fa-exclamation-triangle"></i> 请尽快修改后台初始密码！</h6>';
        }
        return '';
    }

    public function usedspace()
    {
        if ($this->request->isPost()) {
            $dirname = $this->app->getRootPath();

            $dirsize = get_dir_size($dirname);

            return ReUtils::result(['size' => format_bytes($dirsize)]);
        }
    }

    public function clearcache()
    {
        if ($this->request->isPost()) {
            $runtime_path = $this->app->getRootPath() . 'runtime' . DIRECTORY_SEPARATOR;

            try {
                $cache_dir = $runtime_path . 'cache' . DIRECTORY_SEPARATOR;
                $temp_dir = $runtime_path . 'temp' . DIRECTORY_SEPARATOR;

                deldir($cache_dir);
                deldir($temp_dir);
            } catch (\Exception $e) {
                return ReUtils::error($e->getMessage());
            }
            return ReUtils::success('清除成功');
        }
    }

    public function saveIndexButton()
    {
        $param = $this->request->param();

        $menuids = isset($param['checkbox']) ? $param['checkbox'] : [];

        $ids = implode(',', $menuids);

        $tablename = SysMenuModel::getTable();

        $notinsql = "update " . $tablename . " set method=0 where menuid NOT IN (" . $ids . ");";

        $insql = "update " . $tablename . " set method=1 where menuid IN (" . $ids . ");";

        try {
            Db::execute($notinsql);

            Db::execute($insql);
        } catch (Exception $e) {
            return ReUtils::error();
        }

        return ReUtils::success();
    }

    /**
     * 统计文章数
     */
    public function countArticle()
    {
        $nums = ArticleModel::count();

        return ReUtils::result(['nums' => $nums]);
    }

    /**
     * 统计行业应用数
     */
    public function countIndustry()
    {
        $nums = IndustryModel::count();

        return ReUtils::result(['nums' => $nums]);
    }

    /**
     * 统计l留言数量
     */
    public function countGuestBook()
    {
        $nums = GuestBookModel::count();

        return ReUtils::result(['nums' => $nums]);
    }
}
